﻿using Dora.Orm.SqlSugarCore.UnitOfWork;
using Dora.Services.AdminUser.Dto.QueryDto;
using Dora.Services.AdminUser.Dto.ViewDto;
using Dora.Services.AdminUser.Entities;
using Dora.Tools.Enums.AdminUser;
using SqlSugar;
using Surging.Core.Common;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Dora.Services.AdminUser.Repository.Repositorys
{

    /// <summary>
    /// 角色表仓储层
    /// </summary>
    public class RoleRepository : SqlSugarRepository<RoleEntity, Guid>
    {
        private ISugarUnitOfWork _unitOfWork;
        public RoleRepository(ISugarUnitOfWork unitOfWork) : base(unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 分页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageDataList<RoleViewDto>> GetPageList(RoleQueryDto input)
        {
            var pagePredict = _unitOfWork.QueryClient.Queryable<RoleEntity>()
                .Where(p => p.IsDeleted == 0)
                .WhereIF(input.IsEnabled.HasValue&&input.IsEnabled.Value>=0, it => it.IsEnabled == input.IsEnabled)
                .WhereIF(input.SystemId.HasValue, it => it.SystemId == input.SystemId)
                .WhereIF(input.OrgId.HasValue, it => it.OrgId == input.OrgId)
                .WhereIF(input.OrgType.HasValue && input.OrgType.Value == PermissionOrgType.Shop, it => it.OrgType == (int)PermissionOrgType.Shop || it.OrgType == (int)PermissionOrgType.DirectShop)
                .WhereIF(input.OrgType.HasValue && input.OrgType.Value != PermissionOrgType.Shop, it => it.OrgType == (int)input.OrgType.Value)
                .WhereIF(!string.IsNullOrEmpty(input.Keywords), it => it.Name.Contains(input.Keywords.Trim()) || it.RoleNO.Contains(input.Keywords.Trim()) || it.SystemKey.Contains(input.Keywords.Trim()));
            var totalCount = await pagePredict.CountAsync();
            var pageList = await pagePredict.Select((u) => new RoleViewDto
                {
                    Id = u.Id,
                    SystemId = u.SystemId,
                    SystemKey = u.SystemKey,
                    OrgId = u.OrgId,
                    Name = u.Name,
                    RoleNO = u.RoleNO,
                    Sort = u.Sort,
                    IsEnabled = u.IsEnabled,
                    Remark = u.Remark,
                    OrgType = u.OrgType,
                    CreatedUserName =  u.CreatedUserName,
                    CreatedTime = u.CreatedTime
                })
                .OrderBy(it => it.IsEnabled, OrderByType.Desc)
                .OrderBy(it => it.Sort, OrderByType.Desc)
                .OrderBy(it => it.CreatedTime, OrderByType.Desc)
                .ToPageListAsync(input.PageIndex, input.PageSize);
            var page = new PageDataList<RoleViewDto>(totalCount, pageList, input.PageIndex, input.PageSize);
            return page;
        }

        public async Task<bool> BatchDisable(List<Guid> listID, string UpdatedUserName, Guid UpdatedUserId)
        {
            var strSql = $"UPDATE role SET IsEnabled=0,UpdatedUserId=@UpdatedUserId,UpdatedUserName=@UpdatedUserName,UpdatedTime=@UpdatedTime WHERE id IN('{string.Join("','", listID)}')";
            var result = _unitOfWork.ModifyClient.Ado.ExecuteCommand(strSql, new SugarParameter[]{
              new SugarParameter("@UpdatedUserId",UpdatedUserId),
              new SugarParameter("@UpdatedUserName",UpdatedUserName),
              new SugarParameter("@UpdatedTime",DateTime.Now)
            }) > 0;
            return result;
        }
        public async Task<bool> BatchEnable(List<Guid> listID, string UpdatedUserName, Guid UpdatedUserId)
        {
            var strSql = $"UPDATE role SET IsEnabled=1,UpdatedUserId=@UpdatedUserId,UpdatedUserName=@UpdatedUserName,UpdatedTime=@UpdatedTime WHERE id IN('{string.Join("','", listID)}')";
            var result = _unitOfWork.ModifyClient.Ado.ExecuteCommand(strSql, new SugarParameter[]{
              new SugarParameter("@UpdatedUserId",UpdatedUserId),
              new SugarParameter("@UpdatedUserName",UpdatedUserName),
              new SugarParameter("@UpdatedTime",DateTime.Now)
            }) > 0;
            return result;
        }

        public async Task<List<RoleEntity>> GetCreatedList(Guid userId,int? orgId)
        {
            return await _unitOfWork.QueryClient.Queryable<RoleEntity>()
                .Where(p => p.IsDeleted == 0 && p.CreatedUserId == userId)
                .WhereIF(orgId.HasValue,p=>p.OrgId==orgId)
                .OrderBy(p => p.Sort, OrderByType.Desc)
                .ToListAsync();
        }

        /// <summary>
        /// 美程管理系统的用户有权限的角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<RoleEntity>> GetDoraAuthedList(Guid userId)
        {
            var result = _unitOfWork.QueryClient.Queryable<DoraUserRoleMapEntity, RoleEntity>((erm, er) => new object[] {
                JoinType.Inner, erm.RoleId == er.Id
            })
                .Where((erm, er) => userId == erm.UserId && er.IsDeleted == 0)
                .Select((erm, er) => er).ToList();
            return result;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Delete(Guid id)
        {
            var result = await _unitOfWork.ModifyClient.Updateable<RoleEntity>()
                .SetColumns(it => new RoleEntity() { IsDeleted = 1, UpdatedTime = DateTime.Now })
                .Where(it => it.Id == id).ExecuteCommandAsync() > 0;
            return result;
        }

        /// <summary>
        /// 根据用户名获取一个实体
        /// </summary>
        /// <returns></returns>
        public async Task<RoleEntity> GetByRoleNo(string roleNo)
        {
            return await _unitOfWork.QueryClient.Queryable<RoleEntity>().FirstAsync(item => item.RoleNO == roleNo&&item.IsDeleted==0);
        }

        /// <summary>
        /// 角色编号是否存在
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ExistRoleNO(Guid id, string roleNo)
        {
            return await _unitOfWork.QueryClient.Queryable<RoleEntity>().Where(it => it.RoleNO == roleNo && it.IsDeleted == 0 && it.Id != id).CountAsync() > 0;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public new async Task<bool> Update(RoleEntity entity)
        {
            if (entity.SourceRoleId.Equals(Guid.Empty))
            {
                var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
                {
                    it.Name,
                    it.RoleNO,
                    it.Sort,
                    it.Remark,
                    it.UpdatedUserId,
                    it.UpdatedUserName,
                    it.UpdatedTime,
                }).ExecuteCommandAsync() > 0;
                return result;
            }
            else
            {
                var result = await _unitOfWork.ModifyClient.Updateable(entity).UpdateColumns(it => new
                {
                    it.Name,
                    it.RoleNO,
                    it.Sort,
                    it.Remark,
                    it.SourceRoleId,
                    it.UpdatedUserId,
                    it.UpdatedUserName,
                    it.UpdatedTime,
                }).ExecuteCommandAsync() > 0;
                return result;
            }
        }

        /// <summary>
        /// 获取Tas用户在某个机构下有权限的角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<RoleEntity>> GetTasAuthedList(Guid userId,int orgId)
        {
            try
            {
                var result = await _unitOfWork.QueryClient.Queryable<TasUserRoleMapEntity, RoleEntity>((erm, er) => new object[] {
                JoinType.Inner, erm.RoleId == er.Id
            })
                .Where((erm, er) => userId == erm.UserId && erm.OrgId == orgId && er.IsDeleted == 0)
                .Select((erm, er) => er)
                //.OrderBy(erm => erm.Sort, OrderByType.Desc)
                .ToListAsync();
                return result;
            }
            catch(Exception ex)
            {
               
            }
            return null;
        }
    }
}
